<?php

class Server
{
	private static $_instance;
	private static $host;
	private static $port;
	//private static $password;
	private static $list;
	public static  $redisObj;
	public static  $client;

	private function __construct()
	{
		$redis = new Redis();
		$redis->connect(self::$host, self::$port);
		//$redis->auth     = self::$password;
		self::$_instance = $this;
		self::$redisObj  = $redis;

		return self::$_instance;
	}

	//启动redis服务
	public static function instance(array $param)
	{
		self::$host = $param['host'];
		self::$port = $param['port'];
		//self::$password = $param['password'];
		self::$list = $param['list'];
		if (!empty(self::$_instance)) {
			return self::$_instance;
		} else {
			return new self();
		}
	}

	//异步客户端
	public static function client()
	{
		self::$client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
		$res          = self::$client->connect("127.0.0.1", 9502);

		return $res;
	}

	//取出队列里最后一个值并删除
	public function getRes()
	{
		return self::$redisObj->rPop(self::$list);
	}
}

//定时器
swoole_timer_tick(2000, function () {
	$params['host'] = '127.0.0.1';
	$params['port'] = 6379;
	$params['list'] = 'lists';//KEY 为lists
	$Server         = Server::instance($params);
	$redis          = $Server::$redisObj;

	//判断redis是否有数据，没有的话就结束任务
	$res = $redis->lLen('lists');
	if ($res == 0) return;

	//任务 1
	swoole_timer_after(1, function () use ($Server) {
		$res = $Server::getRes();
		//判断redis是否有数据，没有的话就结束任务
		if (empty($res)) return;
		$ret = $Server::client();
		if (empty($ret)) {
			echo '任务推送失败';
		} else {
			$Server::$client->send("推送的任务->1 ->" . $res);
		}
	});

	//任务 2
	swoole_timer_after(200, function () use ($Server) {
		$res = $Server::getRes();

		//判断redis是否有数据，没有的话就结束任务
		if (empty($res)) return;

		$ret = $Server::client();
		if (empty($ret)) {
			echo '任务推送失败';
		} else {
			$Server::$client->send("推送的任务->2 ->" . $res);
		}
	});
	//任务 3
	swoole_timer_after(400, function () use ($Server) {
		$res = $Server::getRes();

		//判断redis是否有数据，没有的话就结束任务
		if (empty($res)) return;

		$ret = $Server::client();
		if (empty($ret)) {
			echo '任务推送失败';
		} else {
			$Server::$client->send("推送的任务->3 ->" . $res);
		}
	});
	//任务 4
	swoole_timer_after(600, function () use ($Server) {
		$res = $Server::getRes();

		//判断redis是否有数据，没有的话就结束任务
		if (empty($res)) return;

		$ret = $Server::client();
		if (empty($ret)) {
			echo '任务推送失败';
		} else {
			$Server::$client->send("推送的任务->4 ->" . $res);
		}
	});

	//任务 5
	swoole_timer_after(800, function () use ($Server) {
		$res = $Server::getRes();

		//判断redis是否有数据，没有的话就结束任务
		if (empty($res)) return;

		$ret = $Server::client();
		if (empty($ret)) {
			echo '任务推送失败';
		} else {
			$Server::$client->send("推送的任务->5 ->" . $res);
		}
	});
});
